package com.right.health.app.ui.me;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.magic.basic.activity.BaseActivity;
import com.magic.basic.utils.CollectionUtil;
import com.magic.basic.utils.ToastUtil;
import com.magics.http.listener.OnHttpListener;
import com.magics.http.model.Request;
import com.magics.http.model.Response;
import com.right.health.app.R;
import com.right.health.app.app.App;
import com.right.health.app.bean.DrugReminderInfo;
import com.right.health.app.bean.FamilyResponse;
import com.right.health.app.bean.PositionInfo;
import com.right.health.app.common.DataCommon;
import com.right.health.app.constants.BroadCastCode;
import com.right.health.app.constants.BroadCastKey;
import com.right.health.app.dialog.BottomPickerDialog;
import com.right.health.app.dialog.CycleTimeBottomDialog;
import com.right.health.app.dialog.DateBottomPickerDialog;
import com.right.health.app.dialog.ListBottomSheetDialog;
import com.right.health.app.dialog.TimeBottomPickerDialog;
import com.right.health.app.net.RemindApi;
import com.right.health.app.ui.me.adapter.CycleTimeBottomAdapter;
import com.right.health.app.ui.me.adapter.DrugReminderAddAdapter;

import java.util.ArrayList;
import java.util.List;

/*
 * Created by hopeliao on 2019-09-29
 *
 * 用药提醒
 */
public class DrugReminderAddActivity extends BaseActivity implements View.OnClickListener, OnHttpListener {
    private static final int HANDLE_TYPE_START_TIME = 1;
    private static final int HANDLE_TYPE_END_TIME = 2;

    private static final int REQUEST_CODE_FAMILY = 1;

    private DrugReminderAddAdapter mAdapter;

    private List<DrugReminderInfo> mDataSource = new ArrayList<>();

    private BottomPickerDialog<BottomPickerDialog.BottomPickerInfo> mPickerDialog;

    private TimeBottomPickerDialog mTimeDialog;
    private DateBottomPickerDialog mDateDialog;

    private CycleTimeBottomDialog mCycleTimeDialog;

    private CycleTimeBottomAdapter mCycleTimeBottomAdapter;

    private TextView mUserTv;

    private int mCycleNum;

    private List<BottomPickerDialog.BottomPickerInfo> mCycleDataSource = new ArrayList<>();

    private RemindApi mRemindApi;

    @Override
    public void onCreate(Bundle bundle, String s) {
        setContentView(R.layout.drug_reminder_add);
    }

    @Override
    public void findView() {
        mUserTv = (TextView) findViewById(R.id.tv_userName);
        findViewById(R.id.tv_save).setOnClickListener(this);

        findViewById(R.id.tv_switch_member).setOnClickListener(this);

        ListView listView = (ListView) findViewById(R.id.listview);
        mAdapter = new DrugReminderAddAdapter(this);
        mAdapter.setOnClickListener(mAdapterClick);
        listView.setAdapter(mAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                startIntent(ReviewReminderDetailActivity.class);
            }
        });

        View footView = LayoutInflater.from(this).inflate(R.layout.review_reminder_add_footer, null);
        footView.findViewById(R.id.ib_add).setOnClickListener(this);
        listView.addFooterView(footView);
    }

    @Override
    public void initialize() {
        mUserTv.setText(App.getInstance().getCurrentMember().name);

        mCycleNum = 0;
        String[] cycleArrays = getResources().getStringArray(R.array.cycle_arrays);
        for(String str:cycleArrays) {
            mCycleDataSource.add(new BottomPickerDialog.BottomPickerInfo(str));
        }

        mRemindApi = new RemindApi();
        mRemindApi.setListener(this);
    }

    private PositionInfo mPositionInfo = new PositionInfo();

    private View.OnClickListener mAdapterClick = v -> {
        switch (v.getId()) {
            case R.id.tv_choose_cycle: //服药周期
                int position = (int) v.getTag();
                getPickerDialog(position).show();
                break;
            case R.id.tv_choose_time: //时间
                if (mCycleNum == 0) {
                    ToastUtil.show(this, "请选择提醒周期");
                    return;
                }
                int index = (int) v.getTag();
                getCycleTimeDialog(index).show();
                break;
            case R.id.tv_start_time: //开始时间
                mPositionInfo.position = (int) v.getTag();
                mPositionInfo.type = HANDLE_TYPE_START_TIME;

                getDateDialog(mPositionInfo).show();
                break;
            case R.id.tv_end_time: //结束时间
                mPositionInfo.position = (int) v.getTag();
                mPositionInfo.type = HANDLE_TYPE_END_TIME;
                getDateDialog(mPositionInfo).show();
                break;
            case R.id.tv_del:
                final int pos = (int) v.getTag();
                final AlertDialog dialog = DataCommon.getDeleteDialog(this, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        mDataSource.remove(pos);
                        mAdapter.setDataSource(mDataSource);
                    }
                });
                dialog.show();
                break;
        }
    };

    private BottomPickerDialog getPickerDialog(int tag) {
        if (mPickerDialog == null) {
            mPickerDialog = new BottomPickerDialog<>(this);
            mPickerDialog.setChooseListener((tag1, num) -> {

                dismissPickerDialog();
                mCycleNum = (num + 1);
                int position = (int) tag1;
                List<DrugReminderInfo> dataSource = mAdapter.getDataSource();

                mDataSource.clear();
                mDataSource.addAll(dataSource);
                DrugReminderInfo drugReminderInfo = mDataSource.get(position);
                drugReminderInfo.cycle = mCycleNum;
                mDataSource.set(position, drugReminderInfo);
                mAdapter.setDataSource(mDataSource);

                mCycleTimeDataSource.clear();

                for (int i = 0; i < mCycleNum; i++) {
                    CycleTimeBottomAdapter.ReminderAddBottomInfo info = new CycleTimeBottomAdapter.ReminderAddBottomInfo();
                    info.name = String.format("第%s次", String.valueOf(i + 1));
                    mCycleTimeDataSource.add(info);
                }
            });
            mPickerDialog.setDataSource(mCycleDataSource);
        }
        mPickerDialog.setTag(tag);
        return mPickerDialog;
    }

    private TimeBottomPickerDialog getTimeDialog(int tag) {
        if (mTimeDialog == null) {
            mTimeDialog = new TimeBottomPickerDialog(this);
            mTimeDialog.setConfirmListener(new TimeBottomPickerDialog.OnConfirmListener() {
                @Override
                public void onConfirm(Object tag, int chooseHour, int chooseMin) {
                    mTimeDialog.dismiss();
                    int position = (int) tag;
                    CycleTimeBottomAdapter.ReminderAddBottomInfo info = mCycleTimeDataSource.get(position);
                    info.chooseHour = chooseHour;
                    info.chooseMinute = chooseMin;
                    info.time = String.format("%s:%s",
                            chooseHour < 10 ? "0" + chooseHour : String.valueOf(chooseHour),
                            chooseMin < 10 ? "0" + chooseMin : String.valueOf(chooseMin));
                    mCycleTimeDataSource.set(position, info);
                    refreshCycleTimeAdapter();
                }
            });
        }
        mTimeDialog.setTag(tag);
        return mTimeDialog;
    }

    private List<CycleTimeBottomAdapter.ReminderAddBottomInfo> mCycleTimeDataSource = new ArrayList<>();

    private ListBottomSheetDialog getCycleTimeDialog(int index) {
        if (mCycleTimeDialog == null) {
            mCycleTimeDialog = new CycleTimeBottomDialog(this);
            mCycleTimeBottomAdapter = new CycleTimeBottomAdapter(this);
            mCycleTimeDialog.setAdapter(mCycleTimeBottomAdapter);
            mCycleTimeDialog.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    getTimeDialog(position).show();
                }
            });
            mCycleTimeDialog.setConfirmListener(tag -> {
                disimissCycleTimeDialog();

                int pos = (int) tag;

                StringBuilder sb = new StringBuilder();
                StringBuilder netData = new StringBuilder();
                DrugReminderInfo drugReminderInfo = mDataSource.get(pos);

                for (int i = 0; i < mCycleTimeDataSource.size(); i++) {
                    CycleTimeBottomAdapter.ReminderAddBottomInfo info = mCycleTimeDataSource.get(i);
                    if (TextUtils.isEmpty(info.time)) {
                        ToastUtil.show(DrugReminderAddActivity.this, "请选择周期对应的提醒时间");
                        return;
                    }
                    sb.append(info.time);
                    netData.append(info.time);

                    if (i != mCycleTimeDataSource.size() - 1) {
                        sb.append(" | ");
                        netData.append(",");
                    }
                }

                List<DrugReminderInfo> dataSource = mAdapter.getDataSource();

                mDataSource.clear();
                mDataSource.addAll(dataSource);

                drugReminderInfo.cycletimes = sb.toString();
                drugReminderInfo.netCycleTimes = netData.toString();
                mDataSource.set(pos, drugReminderInfo);
                mAdapter.setDataSource(mDataSource);

            });
        }
        refreshCycleTimeAdapter();
        mCycleTimeDialog.setTag(index);
        return mCycleTimeDialog;
    }

    private void refreshCycleTimeAdapter() {
        mCycleTimeBottomAdapter.setDataSource(mCycleTimeDataSource);
    }

    private DateBottomPickerDialog getDateDialog(PositionInfo tag) {
        if (mDateDialog == null) {
            mDateDialog = new DateBottomPickerDialog(this);
            mDateDialog.setDelegate((tag1, year, month, date) -> {
                dismissDateDialog();
                PositionInfo positionInfo = (PositionInfo) tag1;

                StringBuilder sb = new StringBuilder();
                sb.append(year).append("-").append(month).append("-").append(date);

                List<DrugReminderInfo> dataSource = mAdapter.getDataSource();

                mDataSource.clear();
                mDataSource.addAll(dataSource);

                DrugReminderInfo info = mDataSource.get(positionInfo.position);
                if (positionInfo.type == HANDLE_TYPE_END_TIME) {
                    info.endtime = sb.toString();
                } else if (positionInfo.type == HANDLE_TYPE_START_TIME) {
                    info.starttime = sb.toString();
                }
                mDataSource.set(positionInfo.position, info);
                mAdapter.setDataSource(mDataSource);
            });
        }
        mDateDialog.setTag(tag);
        return mDateDialog;
    }

    private void dismissPickerDialog() {
        if (mPickerDialog != null && mPickerDialog.isShowing()) {
            mPickerDialog.dismiss();
        }
    }

    private void dismissTimeDialog() {
        if (mTimeDialog != null && mTimeDialog.isShowing()) {
            mTimeDialog.dismiss();
        }
    }

    private void dismissDateDialog() {
        if (mDateDialog != null && mDateDialog.isShowing()) {
            mDateDialog.dismiss();
        }
    }

    private void disimissCycleTimeDialog() {
        if (mCycleTimeDialog != null && mCycleTimeDialog.isShowing()) {
            mCycleTimeDialog.dismiss();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dismissDateDialog();
        dismissTimeDialog();
        dismissPickerDialog();
        disimissCycleTimeDialog();
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.ib_add) {
            if (mAdapter.getDataSource().size() >= 5) {
                ToastUtil.show(this, "一次性最多添加五条用药提醒");
                return;
            }
            if (!CollectionUtil.isEmpty(mAdapter.getDataSource())) {
                mDataSource.clear();
                mDataSource.addAll(mAdapter.getDataSource());
            }

            mDataSource.add(new DrugReminderInfo());

            mAdapter.mSelectedEditTextPosition = -1;
            mAdapter.setDataSource(mDataSource);
        } else if (v.getId() == R.id.tv_save) {
            send2Net();
        } else if(v.getId() == R.id.tv_switch_member) { //切换成员
            FamilyActivity.makeActivity(this, true, REQUEST_CODE_FAMILY);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK) {
            if(requestCode == REQUEST_CODE_FAMILY) {
                Bundle bundle = data.getExtras();
                if(bundle != null ) {
                    FamilyResponse.FamilyInfo familyInfo = bundle.getParcelable(BroadCastKey.DATA);
                    if(familyInfo != null) {
                        mUserTv.setText(familyInfo.membername);
                    }
                }
            }
        }
    }

    private void send2Net() {
        List<DrugReminderInfo> dataSource = mAdapter.getDataSource();
        if (CollectionUtil.isEmpty(dataSource)) {
            ToastUtil.show(this, "请先添加您的用药提醒");
            return;
        }

        for (DrugReminderInfo info : dataSource) {
            if (TextUtils.isEmpty(info.remindname)) {
                ToastUtil.show(this, "请输入药品名称");
                return;
            }
            if (TextUtils.isEmpty(info.starttime)) {
                ToastUtil.show(this, "请选择开始时间");
                return;
            }
            if (TextUtils.isEmpty(info.endtime)) {
                ToastUtil.show(this, "请选择结束时间");
                return;
            }
            if (info.cycle <= 0) {
                ToastUtil.show(this, "请选择服药周期");
                return;
            }
            if (TextUtils.isEmpty(info.netCycleTimes)) {
                ToastUtil.show(this, "请选择服药周期时间");
                return;
            }
        }

        mRemindApi.addDrugRemind(dataSource, App.getInstance().getCurrentMember().id);

    }

    @Override
    public void onResponse(Request request, Response response) {
        if (response.isResponseFail()) {
            ToastUtil.show(this, response.error);
        } else {
            ToastUtil.show(this, R.string.add_succ);
            sendBroadcast(BroadCastCode.RREFRESH_DRUGREINDE);
            finish();
        }
    }
}
